package com.mall.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.mall.common.Result;
import com.mall.common.ResultCode;
import com.mall.dto.UserDTO;
import com.mall.model.User;
import com.mall.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@Tag(name = "认证管理")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
public class AuthController {
    
    private final UserService userService;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        userService.register(user);
        return Result.success();
    }
    
    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<String> login(@Valid @RequestBody UserDTO userDTO) {
        User user = userService.getByUsername(userDTO.getUsername());
        if (user == null) {
            return Result.error(ResultCode.USER_NOT_EXIST);
        }
        
        // 验证密码
        String userDTOPassword = userDTO.getPassword();
        String mysqlPassword = user.getPassword();
        if (!passwordEncoder.matches(userDTOPassword, mysqlPassword)) {
            return Result.error(ResultCode.USER_PASSWORD_ERROR);
        }
        
        // 验证状态
        if (user.getStatus() != 1) {
            return Result.error(ResultCode.USER_ACCOUNT_DISABLED);
        }
        
        // 登录
        StpUtil.login(user.getId());
        return Result.success(StpUtil.getTokenValue());
    }
    
    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    public Result<Void> logout() {
        StpUtil.logout();
        return Result.success();
    }
} 